#ifndef NO_WIDGETS
#include <QFileDialog>
#endif

#include <QBuffer>
#include <QByteArray>
#include <QImage>
#include <QThread>
#include <QFile>
#include <QJsonObject>
#include <QJsonDocument>
#include "qstring.h"
#include "clienthttp.h"
#include "uploadpicvideo.h"
#include "http.h"
#include "clienthttp.h"
#include <QTextCodec>
#include <QJsonObject>
#include <QJsonDocument>
#include "commonfuc.h"
#include "logfile.h"
#include <QThread>


UploadPicVideo::UploadPicVideo(QObject *parent) : QObject(parent)
{
#ifndef NO_WIDGETS
    m_pEdit = NULL;
#endif
    m_bUseNvr = false;
    m_jpg1Path = QString();
    m_jpg2Path = QString();
    m_jpg3Path = QString();
    m_videoPath = QString();
    m_Extension = QString();
    m_videoPathOld = QString();

    m_nPicThreadId = 1;
    m_nVideoThreadId = 1;

    m_pManageThreadPic1 = new QThread;
    m_pUploadPicThread1 = new uploadPicThread;

    m_pUploadPicThread1->moveToThread(m_pManageThreadPic1);
    connect(this, SIGNAL(sigInitPara1(quint64,TRANSFER_INFO)), m_pUploadPicThread1, SLOT(onInitPara(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadPicRequest1(quint64,QString,QByteArray)), m_pUploadPicThread1, SLOT(onDealwithuploadPicRequest(quint64,QString,QByteArray)),Qt::QueuedConnection);

    m_pManageThreadPic1->start();


    m_pManageThreadPic2 = new QThread;
    m_pUploadPicThread2 = new uploadPicThread;

    m_pUploadPicThread2->moveToThread(m_pManageThreadPic2);
    connect(this, SIGNAL(sigInitPara2(quint64,TRANSFER_INFO)), m_pUploadPicThread2, SLOT(onInitPara(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadPicRequest2(quint64,QString,QByteArray)), m_pUploadPicThread2, SLOT(onDealwithuploadPicRequest(quint64,QString,QByteArray)),Qt::QueuedConnection);

    m_pManageThreadPic2->start();

    m_pManageThreadPic3 = new QThread;
    m_pUploadPicThread3 = new uploadPicThread;

    m_pUploadPicThread3->moveToThread(m_pManageThreadPic3);
    connect(this, SIGNAL(sigInitPara3(quint64,TRANSFER_INFO)), m_pUploadPicThread3, SLOT(onInitPara(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadPicRequest3(quint64,QString,QByteArray)), m_pUploadPicThread3, SLOT(onDealwithuploadPicRequest(quint64,QString,QByteArray)),Qt::QueuedConnection);

    m_pManageThreadPic3->start();


    m_pManageThreadVideo = new QThread;
    m_pUploadVideoThread = new uploadVideoThread;

    m_pUploadVideoThread->moveToThread(m_pManageThreadVideo);
    connect(this, SIGNAL(sigInitQiniu(quint64,TRANSFER_INFO)), m_pUploadVideoThread, SLOT(onInitQiniu(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadVideoRequest(quint64,QString,QString,QString,QString,QString)), m_pUploadVideoThread, SLOT(onDealwithuploadVideoRequest(quint64,QString,QString,QString,QString,QString)),Qt::QueuedConnection);

    m_pManageThreadVideo->start();

}

UploadPicVideo::~UploadPicVideo()
{
    /*int i = 0;
    int nSize = m_listPicThread.size();
    for(i = 0; i < nSize; i++)
    {
        if(m_listPicThread.at(i).pManageThread)
        {
            m_listPicThread.at(i).pManageThread->quit();
        }
        if(m_listPicThread.at(i).pWorkThread)
        {
            delete m_listPicThread.at(i).pWorkThread;
            m_listPicThread[i].pWorkThread = NULL;
        }
        if(m_listPicThread.at(i).pManageThread)
        {
            delete m_listPicThread.at(i).pManageThread;
            m_listPicThread[i].pManageThread = NULL;
        }
    }
    m_listPicThread.clear();

    nSize = m_listVideoThread.size();
    for(i = 0; i < nSize; i++)
    {
        if(m_listVideoThread.at(i).pManageThread)
        {
            m_listVideoThread.at(i).pManageThread->quit();
        }
        if(m_listVideoThread.at(i).pWorkThread)
        {
            delete m_listVideoThread.at(i).pWorkThread;
            m_listVideoThread[i].pWorkThread = NULL;
        }
        if(m_listVideoThread.at(i).pManageThread)
        {
            delete m_listVideoThread.at(i).pManageThread;
            m_listVideoThread[i].pManageThread = NULL;
        }
    }
    m_listVideoThread.clear();*/

    /*if(m_pManageThreadPic)
    {
        m_pManageThreadPic->quit();
    }
    if(m_pManageThreadVideo)
    {
        m_pManageThreadVideo->quit();
    }*/
}

#ifndef NO_WIDGETS
void UploadPicVideo::SetEdit(QLineEdit* pEdit)
{	
    m_pEdit = pEdit;
}
#endif

void UploadPicVideo::setIsUseNvr(bool bUseNvr)
{
    m_bUseNvr = bUseNvr;
}

void UploadPicVideo::setTransferInfo(TRANSFER_INFO info)
{
    m_paraInfo = info;
    emit sigInitPara1(1,info);
    emit sigInitPara2(1,info);
    emit sigInitPara3(1,info);
    emit sigInitQiniu(1,info);


    if(-1 != m_paraInfo.persistentOps.indexOf("320x240"))
    {
        m_Extension = QString("_320_240.mp4");;
    }
    else if(-1 != m_paraInfo.persistentOps.indexOf("1280x720"))
    {
        m_Extension = QString("_1280_720.mp4");
    }
    else
    {
         m_Extension = QString(".mp4");
    }
}

void UploadPicVideo::OnLoadPic()
{
}

QString UploadPicVideo::GetMD5ByPic(QString & jpgPath,QByteArray & pic)
{
    QString strLog;
    QString strMd5 = QString();
    pic.clear();
    if(jpgPath.isEmpty() || jpgPath.isNull())
    {
        strLog.sprintf("GetMD5ByPic::Para is NULL!");
        logFile::printLog(strLog);
        return strMd5;
    }


    QBuffer buffer(&pic);
    buffer.open(QIODevice::WriteOnly);
    QImage Image(jpgPath);
    //100为原图大小3倍，80大概为原图大小，50为原图大小一半，-1为原图大小
    bool bOk = Image.save(&buffer ,"JPG", -1);
    if(false == bOk)
    {
        strLog.sprintf("Open jpg failure(%s).!",jpgPath.toStdString().c_str());
        logFile::printLog(strLog);
        return strMd5;
    }

    int nSize = buffer.size();
    strMd5 = QString(QCryptographicHash::hash(pic, QCryptographicHash::Md5).toHex());
    strLog.sprintf("%s MD5:%s;size:%d.",jpgPath.toStdString().c_str(),strMd5.toStdString().c_str(),nSize);
    logFile::printLog(strLog);

    return strMd5;
}

void UploadPicVideo::snapAndGetVideoOK_Slot(QByteArray data, QString jpg1, QString jpg2, QString jpg3, QString videoPath)
{
    QString strLog;
    QString strTmp = data;
    strLog.sprintf("data: %s.",strTmp.toStdString().c_str());
    logFile::printLog(strLog);

    strLog.sprintf("jpg1: %s.", jpg1.toStdString().c_str());
    logFile::printLog(strLog);

    strLog.sprintf("jpg2: %s.", jpg2.toStdString().c_str());
    logFile::printLog(strLog);

    strLog.sprintf("jpg3: %s.", jpg3.toStdString().c_str());
    logFile::printLog(strLog);

    strLog.sprintf("videoPath: %s.", videoPath.toStdString().c_str());
    logFile::printLog(strLog);

    strLog.sprintf("m_bUseNvr: %s.", m_bUseNvr ? "Yes" : "No");
    logFile::printLog(strLog);

    if(m_bUseNvr)
    {
        if(jpg1.isEmpty() || jpg2.isEmpty() || jpg3.isEmpty() || videoPath.isEmpty())
        {
            strLog.sprintf("UseNvr:file path is null!");
            logFile::printLog(strLog);
            return;
        }
    }
    else
    {
        if(jpg1.isEmpty() || jpg2.isEmpty() || jpg3.isEmpty())
        {
            strLog.sprintf("NO UseNvr:file path is null!");
            logFile::printLog(strLog);
            return;
        }

        videoPath = QString();
        m_videoPathOld = QString();
        m_videoPath = QString();
    }


    m_jpg1Path = jpg1;
    m_jpg2Path = jpg2;
    m_jpg3Path = jpg3;
    m_videoPathOld = videoPath;

    //update video name
    if(!videoPath.isEmpty())
    {
        int nleft = videoPath.length() - 4;
        QString strTmpVideo = videoPath.left(nleft);
        m_videoPath = strTmpVideo;
        m_videoPath.append(m_Extension);
    }

    QString fileName;
    if(!m_videoPath.isEmpty())
    {
        //QChar c
        int nLast = m_videoPath.lastIndexOf('/');
        int nCount = m_videoPath.length() - nLast - 1;
        fileName = m_videoPath.right(nCount);
    }

    //Get MD5
    QString jpg1_MD5 = GetMD5ByPic(jpg1,m_pic1);
    QString jpg2_MD5 = GetMD5ByPic(jpg2,m_pic2);
    QString jpg3_MD5 = GetMD5ByPic(jpg3,m_pic3);


    /*JSON:
    {"openTime": "可视对讲开门时间",
    "openDoorNum": "20_33_05_01_20_13_00",
    "openType": 3,
    "userId": "",
    "areaId": "20_33_05_01_00_00_90",
    "doorInfo": "20_33_05_01_00_00_90",
    "pic1":"图片1md5",
    "pic2":"图片2md5",
    "pic3":"图片3md5",
    "videourl":"http://www.xxx.dd"
    }*/


   /* QJsonObject resultjson;
        resultjson.insert("id", jsonObj["id"].toInt());
        resultjson.insert("areaid", m_cfg.m_cfg.general.proxyId);
        resultjson.insert("userid", jsonObj["userid"]);
        resultjson.insert("openMode", jsonObj["openMode"]);
        resultjson.insert("mac",  m_cliMap[sock]);
        QJsonDocument document;
        document.setObject(resultjson);
        //resultData为发给网页后台的信息
        QByteArray resultData = document.toJson(QJsonDocument::Compact);*/


    //QByteArray doorInfo = data.toUtf8();
    QJsonParseError jsonErr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonErr);
    QJsonObject jsonObj = jsonDoc.object();
    jsonObj.insert("pic",jpg1_MD5+","+jpg2_MD5+","+jpg3_MD5);
    QString strVideoUrl;
    strVideoUrl.append(m_paraInfo.externLink);
    strVideoUrl.append(fileName);
    if(m_bUseNvr)
    {
        jsonObj.insert("videourl",strVideoUrl);
    }
    else
    {
        strVideoUrl = QString();
        jsonObj.insert("videourl",strVideoUrl);
    }

    /*QString strTime = CommonFuc::getCurTime();
    jsonObj["openTime"] = strTime;
    jsonObj["openDoorNum"] = "20_33_05_01_20_13_00";
    jsonObj["openType"] = 4;
    jsonObj["userId"] = "123";
    jsonObj["areaId"] = "20_33_05_01_00_00_90";
    jsonObj["doorInfo"] = "20_33_05_01_00_00_90";
    jsonObj["pic"] = jpg1;
    jsonObj["videourl"] = videoPath;*/
    jsonDoc.setObject(jsonObj);
    //const char* pContent = jsonDoc.toJson(QJsonDocument::Compact);
    QString strSendData = jsonDoc.toJson(QJsonDocument::Compact);

    UploadRecordInfo(strSendData);


    //UploadupPicToBackstage();
    //UploadupVideoToQiniu();

}

bool UploadPicVideo::UploadRecordInfo(const QString & json)
{
    //http://192.168.0.235:7890/log/talk?msgJson={"openType":15,"userId":"41507B03674E8A92","openTime":"170628211625","doorInfo":"55_55_01_01_11_11_20","openDoorNum":null,"md5":"f5f95f63fa986274d524a0bc02d9977e,13bd7cad857c74261cb3c8d6226f7c20,27c924ebdb510fbed9c63f162b537700"}

    //组合URL
    QString strUrl = m_paraInfo.backstageUrl;
    strUrl.append(json);

    logFile::printLog(strUrl);

    //启动HTTP请求
    HttpClient* pHttpFun = new HttpClient();
    connect(pHttpFun,SIGNAL(signal_requestFinished(int,bool,const QString&,int)),
            this,SLOT(slot_requestFinished(int,bool,const QString&,int)));

    pHttpFun->sendRequest_Get(strUrl,1);
    //m_nUserData++;

    return true;
}

void UploadPicVideo::slot_requestFinished(int nType,bool bSuccess, const QString& strResult,int userData)
{
    QString strType;
    QString strIsSuccess;
    if(1==nType)
    {
        strType = QString("Get Rsp:");
    }
    else
    {
         strType = QString("Post Rsp:");
    }

    if(bSuccess)
    {
        if(1==nType)
        {
            //上报记录成功后再上传图片和视频
            UploadupPicToBackstage();
            if(m_bUseNvr)
            {
                UploadupVideoToQiniu();
            }
        }
        strIsSuccess = QString(" success ");
    }
    else
    {
        strIsSuccess = QString(" failure ");
    }


    QString strLog = QString("%1%2%3").arg(strType,strIsSuccess,strResult);
    logFile::printLog(strLog);
}

void UploadPicVideo::UploadupPicToBackstage()
{
    QString strLog = QString("Prepare to upload images.");
    logFile::printLog(strLog);

    //int nThreadId = (int)QThread::currentThreadId();

    //AddPicThread(m_jpg1Path,m_pic1);
    //AddPicThread(m_jpg2Path,m_pic2);
    //AddPicThread(m_jpg3Path,m_pic3);
    emit sigUploadPicRequest1(1,m_jpg1Path,m_pic1);
    emit sigUploadPicRequest2(1,m_jpg2Path,m_pic2);
    emit sigUploadPicRequest3(1,m_jpg3Path,m_pic3);
}

void UploadPicVideo::UploadupVideoToQiniu()
{
    QString strLog = QString("Prepare to upload video.");
    logFile::printLog(strLog);

    QFile file(m_videoPathOld);
    file.open(QIODevice::ReadOnly);
    qint64 nFileSize = file.size();
    if(0 == nFileSize)
    {
        strLog.sprintf("error:%s size is 0",m_videoPathOld.toStdString().c_str());
        logFile::printLog(strLog);
        file.close();
        return;
    }
    else if(nFileSize > 100 * 1024 * 1024)
    {
        strLog.sprintf("error:%s size is %lld(too big!)",m_videoPathOld.toStdString().c_str(),nFileSize);
        logFile::printLog(strLog);
        file.close();
        return;
    }

    strLog.sprintf("%s size is %lld",m_videoPathOld.toStdString().c_str(),nFileSize);
    logFile::printLog(strLog);

    file.close();


    //AddVideoThread(m_videoPath);
    emit sigUploadVideoRequest(1,m_videoPathOld,m_videoPath,m_jpg1Path,m_jpg2Path,m_jpg3Path);
}

/*void UploadPicVideo::AddPicThread(QString picPath,QByteArray pic)
{
    QString strLog;
    QThread* pManageThread = new QThread;
    uploadPicThread* pWorkThread = new uploadPicThread;

    if(NULL == pManageThread || NULL == pWorkThread)
    {
        strLog.sprintf("AddPicThread para is null(pManageThread=%d,pWorkThread=%d).",pManageThread,pWorkThread);
        logFile::printLog(strLog);
        return;
    }

    PicWorkThreadInfo info;
    info.pManageThread = pManageThread;
    info.pWorkThread = pWorkThread;
    info.nId = m_nPicThreadId;
    m_nPicThreadId++;
    m_listPicThread.push_back(info);

    pWorkThread->moveToThread(pManageThread);
    connect(this, SIGNAL(sigInitPara(quint64,TRANSFER_INFO)), pWorkThread, SLOT(onInitPara(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadPicRequest(quint64,QString,QByteArray)), pWorkThread, SLOT(onDealwithuploadPicRequest(quint64,QString,QByteArray)),Qt::QueuedConnection);
    connect(pWorkThread, SIGNAL(sigPicWorkFinish(quint64)), this, SLOT(onPicWorkFinish(quint64)),Qt::QueuedConnection);
    pManageThread->start();

    Sleep(100);

    emit sigInitPara(info.nId,m_paraInfo);

    strLog.sprintf("AddPicThread id = %lld, m_listPicThread size = %d.",m_nPicThreadId-1,m_listPicThread.size());
    logFile::printLog(strLog);

    emit sigUploadPicRequest(info.nId,picPath,pic);
}

void UploadPicVideo::AddVideoThread(QString videoPath)
{
    QString strLog;
    QThread* pManageThread = new QThread;
    uploadVideoThread* pWorkThread = new uploadVideoThread;

    if(NULL == pManageThread || NULL == pWorkThread)
    {
        strLog.sprintf("AddVideoThread para is null(pManageThread=%d,pWorkThread=%d).",pManageThread,pWorkThread);
        logFile::printLog(strLog);
        return;
    }


    VideoWorkThreadInfo info;
    info.pManageThread = pManageThread;
    info.pWorkThread = pWorkThread;
    info.nId = m_nVideoThreadId;
    m_nVideoThreadId++;

    m_listVideoThread.push_back(info);

    pWorkThread->moveToThread(pManageThread);

    connect(this, SIGNAL(sigInitQiniu(quint64,TRANSFER_INFO)), pWorkThread, SLOT(onInitQiniu(quint64,TRANSFER_INFO)),Qt::QueuedConnection);
    connect(this, SIGNAL(sigUploadVideoRequest(quint64,QString)), pWorkThread, SLOT(onDealwithuploadVideoRequest(quint64,QString)),Qt::QueuedConnection);
    connect(pWorkThread, SIGNAL(sigVideoWorkFinish(quint64)), this, SLOT(onVideoWorkFinish(quint64)),Qt::QueuedConnection);
    pManageThread->start();

    Sleep(100);

    emit sigInitQiniu(info.nId,m_paraInfo);

    Sleep(100);

    strLog.sprintf("AddVideoThread id = %lld, m_listVideoThread size = %d.",m_nVideoThreadId-1,m_listVideoThread.size());
    logFile::printLog(strLog);

    emit sigUploadVideoRequest(info.nId,videoPath);
}

void UploadPicVideo::onPicWorkFinish(quint64 id)
{
    int i = 0;
    bool bExist = false;
    int nSize = m_listPicThread.size();
    for(i = 0; i < nSize; i++)
    {
        if(id == m_listPicThread.at(i).nId)
        {
            bExist = true;
            break;
        }
    }

    if(bExist)
    {
        if(m_listPicThread.at(i).pManageThread)
        {
            m_listPicThread.at(i).pManageThread->quit();
        }
        if(m_listPicThread.at(i).pWorkThread)
        {
            delete m_listPicThread.at(i).pWorkThread;
            m_listPicThread[i].pWorkThread = NULL;
        }
        if(m_listPicThread.at(i).pManageThread)
        {
            delete m_listPicThread.at(i).pManageThread;
            m_listPicThread[i].pManageThread = NULL;
        }
        m_listPicThread.removeAt(i);

        QString strLog;
        strLog.sprintf("DeletePicThread id = %lld, m_listPicThread size = %d.",id,m_listPicThread.size());
    }
}

void UploadPicVideo::onVideoWorkFinish(quint64 id)
{
    int i = 0;
    bool bExist = false;
    int nSize = m_listVideoThread.size();
    for(i = 0; i < nSize; i++)
    {
        if(id == m_listVideoThread.at(i).nId)
        {
            bExist = true;
            break;
        }
    }

    if(bExist)
    {
        if(m_listVideoThread.at(i).pManageThread)
        {
            m_listVideoThread.at(i).pManageThread->quit();
        }
        if(m_listVideoThread.at(i).pWorkThread)
        {
            delete m_listVideoThread.at(i).pWorkThread;
            m_listVideoThread[i].pWorkThread = NULL;
        }
        if(m_listVideoThread.at(i).pManageThread)
        {
            delete m_listVideoThread.at(i).pManageThread;
            m_listVideoThread[i].pManageThread = NULL;
        }
        m_listVideoThread.removeAt(i);
        QString strLog;
        strLog.sprintf("DeleteVideoThread id = %lld, m_listVideoThread size = %d.",id,m_listVideoThread.size());
    }
}*/

